#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include "mysql.h"

// 服务器监听的端口号
#define PORT 8889

// 声明 query_data 函数
char *query_data(MYSQL *connect, char *table, char *query_condition);

// 处理客户端连接的服务器函数
void handle_server_connection() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    char buffer[1024];
    char *response;

    // 创建服务器套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Error creating server socket");
        return;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定套接字到指定地址和端口
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error binding server socket");
        close(server_socket);
        return;
    }

    // 监听连接请求
    if (listen(server_socket, 5) == -1) {
        perror("Error listening for connections");
        close(server_socket);
        return;
    }

    printf("Server listening on port %d...\n", PORT);

    // 接受客户端连接
    client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
    if (client_socket == -1) {
        perror("Error accepting client connection");
        close(server_socket);
        return;
    }

    printf("Client connected.\n");

    // 连接数据库
    MYSQL *db_connection = connect_to_mysql();

    while (1) {
        // 接收客户端请求
        ssize_t bytes_read = read(client_socket, buffer, sizeof(buffer) - 1);
        if (bytes_read <= 0) {
            perror("Error reading from client");
            break;
        }
        buffer[bytes_read] = '\0';
        char *table_name;

        // 假设客户端发送的信号是特定格式，如"operation:table_name:data"
        char *token = strtok(buffer, ":");
        if (token && strcmp(token, "insert") == 0) {
            token = strtok(NULL, ":");
            if (token) {
                table_name = token;
                token = strtok(NULL, ":");
                if (token) {
                    if (strcmp(table_name, "login") == 0) {
                        Login pro;
                        sscanf(token, "%d %d %s %s", &pro.type, &pro.res, pro.account, pro.password);
                        insert_login_data(db_connection, pro);
                    } else if (strcmp(table_name, "info") == 0) {
                        Info infor;
                        sscanf(token, "%d %d %f %f %f %f %f %f %s %s %s %s", &infor.type, &infor.res, &infor.temp, &infor.humidity, &infor.O2, &infor.CO2, &infor.CH4, &infor.CO, infor.time, infor.pt, infor.principal, infor.state);
                        insert_info_data(db_connection, infor);
                    } else if (strcmp(table_name, "Instrument") == 0) {
                        Instrument data;
                        sscanf(token, "%d %s %s %s %s %s %s", &data.id, data.name, data.contact_way, data.Instrument_number, data.bor_time, data.ret_time, data.state);
                        insert_instrument_data(db_connection, data);
                    } else if (strcmp(table_name, "Safety_officer") == 0 || strcmp(table_name, "manager") == 0) {
                        Message message;
                        sscanf(token, "%s %s %s %s %s %s", message.name, message.gender, message.age, message.telephone, message.account, message.password);
                        insert_message_data(db_connection, message, table_name);
                    }
                    response = strdup("Data inserted successfully.");
                } else {
                    response = strdup("Invalid data.");
                }
            } else {
                response = strdup("Invalid table name.");
            }
        } else if (token && strcmp(token, "query") == 0) {
            token = strtok(NULL, ":");
            if (token) {
                table_name = token;
                token = strtok(NULL, ":");
                if (token) {
                    char *query_condition = token;
                    response = query_data(db_connection, table_name, query_condition);
                } else {
                    response = strdup("Invalid query condition.");
                }
            } else {
                response = strdup("Invalid table name.");
            }
        } else {
            response = strdup("Invalid signal.");
        }

        // 发送响应给客户端
        ssize_t bytes_sent = write(client_socket, response, strlen(response));
        if (bytes_sent <= 0) {
            perror("Error writing to client");
        }

        free(response);
    }

    mysql_close(db_connection);
    close(client_socket);
    close(server_socket);
}

int main() {
    handle_server_connection();
    return 0;
}


